package com.shanghaionstar.nav.presenter;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.view.View;

import com.onstar.cn.auth.userProfile.FeatureEnum;
import com.onstar.cn.common.exception.HttpException;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.DeviceUtil;
import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.framework.mvp.base.IMVPScheduler;
import com.onstar.cn.framework.mvp.base.IMVPView;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.framework.utils.RxBus;
import com.onstar.cn.mag.enumtype.RemoteCommandsType;
import com.onstar.cn.mag.poi.Coordinate;
import com.onstar.cn.mag.poi.FavoriteEntity;
import com.onstar.cn.sqlite.entities.PoiSearchHistory;
import com.onstar.cn.sqlite.entities.UserAddressEntity;
import com.onstar.cn.map.common.LocationType;
import com.onstar.cn.map.common.PoiItemInfo;
import com.onstar.cn.map.common.PoiType;
import com.onstar.cn.rxconstants.RxConstants;
import com.onstar.cn.vehicle.entity.ErrorInfo;
import com.shanghaionstar.R;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.nav.NavChoosePointInMapFragment;
import com.shanghaionstar.nav.NavMainFragment;
import com.shanghaionstar.nav.NavMapFragment;
import com.shanghaionstar.nav.NavSearchMoreFragment;
import com.shanghaionstar.nav.NavSearchTypeFragment;
import com.shanghaionstar.nav.NavSetAddressFragment;
import com.shanghaionstar.nav.adapter.NavPoiSearchHistoryAdapter;
import com.shanghaionstar.nav.iview.INavMainView;
import com.shanghaionstar.nav.model.MapChoosePoiType;
import com.shanghaionstar.nav.model.NavInfoModel;
import com.shanghaionstar.nav.model.PoiHistoryInfo;
import com.shanghaionstar.nav.service.AbstractMapActivity;
import com.shanghaionstar.nav.service.NavService;
import com.shanghaionstar.sqlite.SearchHistoryImpl;
import com.shanghaionstar.sqlite.TBTHistoryImpl;
import com.shanghaionstar.pin.PinDialogFragment;
import com.shanghaionstar.sqlite.UserAddressInfoImpl;
import com.shanghaionstar.report.bean.ReportReqParam;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.AuthorUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.ErrorCodeUtil;
import com.shanghaionstar.utils.FinalConfigParams;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.utils.LoadCityList;
import com.shanghaionstar.utils.MapHandler;
import com.shanghaionstar.utils.NavHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.functions.Action1;

/**
 * Created by 6335yz on 2016/7/7.
 */
public class NavMainPresenter extends BasePresenter implements MapHandler.OnMapSearchCallBack {

    private AbstractMapActivity mapActivity;
    private Resources res;
    private INavMainView navMainView;

    private MapHandler mapHandler;

    private List<PoiItemInfo> searchPoiList = new ArrayList<>();
    private FragmentManager fragmentManager;
    private NavService navService;

    private List<PoiSearchHistory> searchHistoryDataLists = new ArrayList<PoiSearchHistory>();

    private List<FavoriteEntity> searchFavLists = new ArrayList<FavoriteEntity>();

    private SearchHistoryImpl searchHistoryImpl;
    private NavPoiSearchHistoryAdapter historyAdapter;
    private UserAddressInfoImpl mUserAddressInfoImpl;
    private List<UserAddressEntity> userAddressInfoList;

    @Override
    public void setView(IMVPView view) {
        super.setView(view);
        navMainView = (INavMainView) view;
    }

    public NavMainPresenter(IMVPScheduler mvpScheduler, AbstractMapActivity mapActivity, MapHandler mapHandler) {
        super(mvpScheduler);
        this.mapActivity = mapActivity;
        this.mapHandler = mapHandler;
        res = this.mapActivity.getResources();
        this.mapHandler.registOnMapSearchCallBack(this);
        fragmentManager = mapActivity.getSupportFragmentManager();
        navService = new NavService(mapActivity);
        searchHistoryImpl = new SearchHistoryImpl(mapActivity);
        mUserAddressInfoImpl = new UserAddressInfoImpl(mapActivity);
//        pinCallBack();
    }

//    private Subscription navMainPageSubscription;
//
//    public void pinCallBack() {
//        /**
//         * 从pin码页面返回
//         */
//        navMainPageSubscription = RxBus.getDefault().toObserverable(RxConstants.NAV_MAIN_PAGE, PinModel.class).filter(new Func1<PinModel, Boolean>() {
//            @Override
//            public Boolean call(PinModel pinModel) {
//                return pinModel.isPinSuccess();
//            }
//        }).subscribeOn(mvpScheduler.backgroundThread())
//                .observeOn(mvpScheduler.mainThread()).subscribe(new Action1<PinModel>() {
//            @Override
//            public void call(PinModel pinModel) {
//                if (pinModel.isPinSuccess()) {
//                    getVehicleLocation();
//                }
//            }
//        });
//    }

    /**
     * 加载搜索选项栏
     */
    public void loadSearchItem(int[] gridViewImages, String[] gridViewTextInfos) {
        List<Map<String, Object>> items = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < gridViewImages.length; i++) {
            Map<String, Object> item = new HashMap<String, Object>();
            item.put("grid_image", gridViewImages[i]);
            item.put("text_item_info", gridViewTextInfos[i]);
            items.add(item);
        }
        if (navMainView != null) {
            navMainView.showSearchItem(items);
        }
    }

    public void search(String searchName) {
        /**
         * 清除上一轮查询数据
         */
        searchPoiList.clear();
        if (CommonUtil.isNull(searchName)) {
            if (navMainView != null) {
                navMainView.onResponseError(new OnStarException("", mapActivity.getString(R.string.poi_not_search_not_condition)));
            }
        } else {
            searchName = searchName.trim();
            if (navMainView != null) {
                navMainView.showMapLoading(true, mapActivity.getString(R.string.poi_searching));
                mapHandler.searchByName(searchName, PoiType.All.getStringValue(), NavHolder.getInstance(mapActivity).getCurrentCity());
            }
        }
    }

    /**
     * 搜索结果回调
     *
     * @param results
     * @param pageIndex
     * @param totalPages
     */
    @Override
    public void onSearchSuccess(List<PoiItemInfo> results, int pageIndex, int totalPages) {
        if (navMainView != null) {
            navMainView.showMapLoading(false, "");
            searchPoiList.addAll(results);
            if (results != null && results.size() > 0) {
                navMainView.showSearchResult(searchPoiList);
            } else {
                navMainView.showSearchResultWithNodata();
            }
        }
    }

    @Override
    public void onSearchFail(LocationType locationType) {

    }

    public void onresume() {
    }

    /**
     * 搜索结果
     *
     * @param * @param
     */
    public void showPoiToMap(PoiItemInfo poiItemInfo, LocationType locationType) {
        searchHistoryImpl.saveSearchHistory(poiItemInfo);
        RxBus.getDefault().post(RxConstants.ALL_PAGE_REFRESH, RxConstants.NAV_SAVE_POI);
        mapActivity.getNavDataHolder().setCurrentMapPoi(poiItemInfo);
        mapActivity.showPoiToMap(poiItemInfo, locationType);
    }

    public void onGridViewItemClick(int position, String[] gridViewTextInfos, View view) {
        NavSearchTypeFragment navSearchTypeFragment;
        switch (position) {
            case 0:// 交通设施
                BusinessUtil.sendReportByClickType(mapActivity, FunctionNameFindId.Mytrip_Transportation.getStringValue());
                navSearchTypeFragment = NavSearchTypeFragment.newInstance(gridViewTextInfos[position], PoiType.Traffic.getStringValue());
                mapActivity.addFragment(fragmentManager, navSearchTypeFragment, true);
                mapActivity.showFragment(fragmentManager, NavSearchTypeFragment.class, NavMainFragment.class);
                break;
            case 1://  餐饮住宿
                BusinessUtil.sendReportByClickType(mapActivity, FunctionNameFindId.Mytrip_Searchpoi_Clickfoodlodging.getStringValue());
                navSearchTypeFragment = NavSearchTypeFragment.newInstance(gridViewTextInfos[position], PoiType.RoomAndBoard.getStringValue());
                mapActivity.addFragment(fragmentManager, navSearchTypeFragment, true);
                mapActivity.showFragment(fragmentManager, NavSearchTypeFragment.class, NavMainFragment.class);
                break;
            case 2:// 购物商场
                BusinessUtil.sendReportByClickType(mapActivity, FunctionNameFindId.Mytrip_Searchpoi_Clickshopping.getStringValue());
                navSearchTypeFragment = NavSearchTypeFragment.newInstance(gridViewTextInfos[position], PoiType.Shopping.getStringValue());
                mapActivity.addFragment(fragmentManager, navSearchTypeFragment, true);
                mapActivity.showFragment(fragmentManager, NavSearchTypeFragment.class, NavMainFragment.class);
                break;
            case 3:// 生活服务
                BusinessUtil.sendReportByClickType(mapActivity, FunctionNameFindId.Mytrip_Searchpoi_livingservice.getStringValue());
                navSearchTypeFragment = NavSearchTypeFragment.newInstance(gridViewTextInfos[position], PoiType.Dailylife.getStringValue());
                mapActivity.addFragment(fragmentManager, navSearchTypeFragment, true);
                mapActivity.showFragment(fragmentManager, NavSearchTypeFragment.class, NavMainFragment.class);
                break;
            case 4:// 更多
                BusinessUtil.sendReportByClickType(mapActivity, FunctionNameFindId.Mytrip_Searchpoi_morecategorysearch.getStringValue());
//                ActivityOptionsCompat.makeSceneTransitionAnimation(mapActivity, view, res.getString(R.string.trans_nav_more));
//                view.setTransitionName(res.getString(R.string.trans_nav_more));
//                ViewCompat.setTransitionName(view,res.getString(R.string.trans_nav_more));
//                mapActivity.addFragmentWithAnimation(fragmentManager, new NavSearchMoreFragment(), view,res.getString(R.string.trans_nav_more));
                mapActivity.addFragment(fragmentManager, new NavSearchMoreFragment(), true);
                mapActivity.showFragment(fragmentManager, NavSearchMoreFragment.class, NavMainFragment.class);
                break;
        }
    }

    public void findVehicleLocation() {
//        BusinessUtil.sendReportByClickType(mapActivity, FunctionNameFindId.GetVehicleLocationButton.getStringValue());
        if (validateVehicleCommand()) {
            showPinOrNot(fragmentManager);
        }
    }

    private boolean validateVehicleCommand() {
        if (!CommonUtil.checkNetWorkState(mapActivity)) return false;
        if (!BusinessUtil.checkOwnerAndShowDialog(mapActivity, navMainView)) return false;
        if (!BusinessUtil.checkPackageRight(Constants.ENTITLEMENT_M06FIND_CAR, mapActivity, true))
            return false;
        if (!ApplicationUtil.getInstance().isBBWC()) {
            if (navMainView != null) {
                navMainView.onResponseError(new OnStarException("", mapActivity.getString(R.string.vehicle_bbwc_error)));
            }
            return false;
        }
        if (!ApplicationUtil.getInstance().isFmvOpt()) {
            if (navMainView != null) {
                navMainView.onResponseError(new OnStarException("", mapActivity.getString(R.string.opt_out_alert)));
            }
            return false;
        }
        if (BusinessUtil.checkInProgressCommand(mapActivity, null)) return false;// 传空代表遥控页的操作
        return !BusinessUtil.checkInProgressCommand(mapActivity, RemoteCommandsType.COMMANDS_LOCATION);
    }

    public void getVehicleLocation() {
        mapActivity.showFragment(fragmentManager, NavMapFragment.class, NavMainFragment.class);
        NavInfoModel navInfoModel = new NavInfoModel();
        navInfoModel.remoteCommandsType = RemoteCommandsType.COMMANDS_LOCATION;
        subscription = navService.doNavCommand(navInfoModel)
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        if (navMainView != null) {
                            navMainView.showMapLoading(false, mapActivity.getString(R.string.locationing_vehicle));
                            navMainView.showCommandLoading(true);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        //里面抛出的Error信息
                        if (navMainView != null) {
                            BusinessUtil.sendReportByRequestParams(mapActivity, FunctionNameFindId.Mytrip_Navigation.getStringValue(), ReportReqParam.getVehicleLocateReqParam(FunctionNameFindId.Mytrip_Locator, false, throwable.getMessage()));
                            navMainView.showMapLoading(false, "");
                            navMainView.onResponseError((OnStarException) throwable);
                        }
                    }
                });
    }

    public void showPinOrNot(FragmentManager fragmentManager) {
        if (BusinessUtil.isAutoSendPin(RemoteCommandsType.COMMANDS_LOCATION, mapActivity)) {
            if (navMainView != null) {
                navMainView.showMapLoading(true, mapActivity.getString(R.string.locationing_vehicle));
            }
            getVehicleLocation();
        } else {
            showPinDialogFragment(fragmentManager);
        }
    }

    private void showPinDialogFragment(FragmentManager fragmentManager) {
        PinDialogFragment pinDialogFragment = PinDialogFragment.newInstance(RemoteCommandsType.COMMANDS_LOCATION, RxConstants.NAV_MAIN_PAGE);
//        pinDialogFragment.registPinCallBack(new PinDialogFragment.OnPinCallBack() {
//            @Override
//            public void onPinSuccess() {
//                getVehicleLocation();
//            }
//
//            @Override
//            public void onPinFail() {
//
//            }
//        });
        pinDialogFragment.show(fragmentManager, "pin_dialog");
    }

    public void clearHistory() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mapActivity, android.app.AlertDialog.THEME_HOLO_LIGHT);
        builder.setMessage(res.getString(R.string.poi_need_clear));
        builder.setPositiveButton(res.getString(R.string.submit), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                if (searchHistoryDataLists != null && searchHistoryDataLists.size() > 0) {
                    searchHistoryImpl.deleteAll();
                    searchHistoryDataLists.clear();
                    if (navMainView != null) {
                        RxBus.getDefault().post(RxConstants.ALL_PAGE_REFRESH, RxConstants.NAV_SAVE_POI);
                        navMainView.showSearchHistory(searchHistoryDataLists);
                        navMainView.showHis(true);
                        navMainView.hisHasData(false);
                    }
                }
            }
        });

        builder.setNegativeButton(res.getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setCancelable(true);
        builder.show();
    }

    public void getHistoryData() {
        searchHistoryDataLists = searchHistoryImpl.getSearchList();
        if (navMainView != null) {
            navMainView.showSearchHistory(searchHistoryDataLists);
            navMainView.showHis(true);
            if (searchHistoryDataLists == null || searchHistoryDataLists.size() == 0) {
                navMainView.hisHasData(false);
            } else {
                navMainView.hisHasData(true);
            }
        }
    }

    public void doGetFavList() {
        searchFavLists.clear();
        if (navMainView != null) {
            navMainView.favLoading(true);
            navMainView.showHis(false);
            /**
             * 首先清空显示的list，使加载进度条能完全覆盖fav layout
             */
            navMainView.showSearchFav(new ArrayList<FavoriteEntity>());
        }
        subscription = navService.doGetFavList()
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<List<FavoriteEntity>>() {
                    @Override
                    public void call(List<FavoriteEntity> favoriteEntities) {
                        searchFavLists = favoriteEntities;
                        navMainView.showHis(false);
                        if (!CommonUtil.isNull(favoriteEntities) && favoriteEntities.size() > 0) {
                            if (navMainView != null) {
                                navMainView.showSearchFav(favoriteEntities);
                            }
                        }
                        if (navMainView != null) {
                            navMainView.favLoading(false);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        if (navMainView != null) {
                            navMainView.showHis(false);
                            navMainView.onResponseError(new OnStarException("", mapActivity.getString(R.string.nav_no_favorite_data)));
                            navMainView.favLoading(false);
                        }
                    }
                });
    }

    public void favDataShowInMap(PoiSearchHistory poiSearchHistory, LocationType locationType) {
        mapActivity.hideSoftInput();
//        BusinessUtil.sendReportByClickType(mapActivity, FunctionNameFindId.Searchpoi_clickhistory.getStringValue());
        PoiItemInfo poiItemInfo = searchHistoryImpl.PoiSearchHistoryToPoiItemInfo(poiSearchHistory);
        searchHistoryImpl.updateSearchHistory(poiItemInfo);
        String city = poiItemInfo.getCityName();
        if (DeviceUtil.getLanguage().equalsIgnoreCase("en")) {
            LoadCityList cityList = new LoadCityList(mapActivity);
            city = cityList.findByZhCity(poiItemInfo.getCityName());
        }
        poiItemInfo.setCityName(city);
        showPoiToMap(poiItemInfo, locationType);
    }

    public void sendTbtOrOdd(final PoiItemInfo poiItemInfo) {
        if(ApplicationUtil.getInstance().isCommanding){
            ApplicationUtil.getInstance().controlCommand(mapActivity);
            return;
        }else{
            ApplicationUtil.getInstance().isCommanding = true;
        }
        NavInfoModel navInfoModel = new NavInfoModel();
        if (BusinessUtil.isServiceFeature(FeatureEnum.SENDNAVDESTINATION.value(), mapActivity)) {
            if (PreferencesUtls.getInstance(mapActivity).getBoolean(FinalConstants.SharedPreferencesConfig.TBT_CHOOSE_SAVE, true)) {
                navInfoModel.remoteCommandsType = RemoteCommandsType.COMMANDS_TBT_ROUTE;
            } else if (PreferencesUtls.getInstance(mapActivity).getBoolean(FinalConstants.SharedPreferencesConfig.ODD_CHOOSE_SAVE, false)) {
                navInfoModel.remoteCommandsType = RemoteCommandsType.COMMANDS_NAV_DESTINATION;
            }
        } else {
            navInfoModel.remoteCommandsType = RemoteCommandsType.COMMANDS_TBT_ROUTE;
        }
        navInfoModel.poiItemInfo = poiItemInfo;
        if (validateTbtOrOdd(poiItemInfo, navInfoModel.remoteCommandsType)) {
            new AuthorUtil().reauthForNoPin(mapActivity, new Action1() {
                @Override
                public void call(Object o) {
                    NavInfoModel tmp = new NavInfoModel();
                    if (BusinessUtil.isServiceFeature(FeatureEnum.SENDNAVDESTINATION.value(), mapActivity)) {
                        if (PreferencesUtls.getInstance(mapActivity).getBoolean(FinalConstants.SharedPreferencesConfig.TBT_CHOOSE_SAVE, true)) {
                            tmp.remoteCommandsType = RemoteCommandsType.COMMANDS_TBT_ROUTE;
                        } else if (PreferencesUtls.getInstance(mapActivity).getBoolean(FinalConstants.SharedPreferencesConfig.ODD_CHOOSE_SAVE, false)) {
                            tmp.remoteCommandsType = RemoteCommandsType.COMMANDS_NAV_DESTINATION;
                        }
                    } else {
                        tmp.remoteCommandsType = RemoteCommandsType.COMMANDS_TBT_ROUTE;
                    }
                    tmp.poiItemInfo = poiItemInfo;
                    doNavCommand(tmp);
                }
            }, new Action1<Throwable>() {
                @Override
                public void call(Throwable throwable) {
                    ApplicationUtil.getInstance().isCommanding = false;
                    RemoteCommandsType tmp = RemoteCommandsType.COMMANDS_TBT_ROUTE;
                    if (BusinessUtil.isServiceFeature(FeatureEnum.SENDNAVDESTINATION.value(), mapActivity)) {
                        if (PreferencesUtls.getInstance(mapActivity).getBoolean(FinalConstants.SharedPreferencesConfig.TBT_CHOOSE_SAVE, true)) {
                            tmp = RemoteCommandsType.COMMANDS_TBT_ROUTE;
                        } else if (PreferencesUtls.getInstance(mapActivity).getBoolean(FinalConstants.SharedPreferencesConfig.ODD_CHOOSE_SAVE, false)) {
                            tmp = RemoteCommandsType.COMMANDS_NAV_DESTINATION;
                        }
                    } else {
                        tmp = RemoteCommandsType.COMMANDS_TBT_ROUTE;
                    }
                    BusinessUtil.sendReportByRequestParams(mapActivity, FunctionNameFindId.SendingTBT.getStringValue(), ReportReqParam.getTBTOddReportParams(tmp, false, throwable.getMessage()));
                    if (navMainView != null) {
                        ErrorInfo errorInfo = ErrorCodeUtil.getErrorInfoByHttpException(mapActivity, new HttpException("", throwable.getMessage()));
                        navMainView.onResponseError(new OnStarException("", errorInfo.getMsg()));
                    }
                }
            });
        }
    }

    private boolean validateTbtOrOdd(PoiItemInfo poiItemInfo, RemoteCommandsType remoteCommandsType) {
        if (poiItemInfo == null) return false;
        if (remoteCommandsType != RemoteCommandsType.COMMANDS_TBT_ROUTE && remoteCommandsType != RemoteCommandsType.COMMANDS_NAV_DESTINATION)
            return false;
        if (!ApplicationUtil.getInstance().isLogin())
            return false;
        if (ApplicationUtil.getInstance().isAutoLogings()) {
            if (navMainView != null) {
                navMainView.onResponseError(new OnStarException("", mapActivity.getString(R.string.loading)));
            }
        }
        if (!BusinessUtil.checkDriverOrProxyAndShowDialog(mapActivity)) {
            return false;
        }
        if (!BusinessUtil.checkPackageRight(Constants.ENTITLEMENT_M05NAVIGATION, mapActivity, true)) {
            return false;
        }
        //判断是否正在执行车辆的相关操作
        if (BusinessUtil.checkInProgressCommand(mapActivity, null, false)) {
            AlertDialogUtil.showAlertDialog(mapActivity, mapActivity.getString(R.string.dialog_warning),
                    mapActivity.getString(R.string.service_inProcess_alert));
//            BusinessUtil.updateConfigValue(FinalConfigParams.SHARE_DESTINATION, "-1", mapActivity);
            return false;
        }
        return true;
    }

    private void doNavCommand(final NavInfoModel navInfoModel) {
        BusinessUtil.sendReportByClickType(mapActivity, FunctionNameFindId.Mytrip_Navigation.getStringValue());
        subscription = navService.doNavCommand(navInfoModel)
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String requestId) {
                        if (navInfoModel.remoteCommandsType == RemoteCommandsType.COMMANDS_NAV_DESTINATION || navInfoModel.remoteCommandsType == RemoteCommandsType.COMMANDS_TBT_ROUTE) {
                            saveHistoryToSql(requestId, navInfoModel.poiItemInfo, null, true);
                            //将下发历史保存到历史记录中
                            saveSearchHistory(navInfoModel.poiItemInfo);
                        }
                        if (navMainView != null) {
                            navMainView.showCommandLoading(true);
                        }
                        NavHolder.getInstance(mapActivity).setCurrentSendPoi(navInfoModel.poiItemInfo);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        //里面抛出的Error信息
                        if (navMainView != null) {
                            navMainView.onResponseError((OnStarException) throwable);
                            if (ApplicationUtil.isActivityFront()) {
                                navMainView.showAppFrontNavCommandFailToast(NavHolder.getInstance(mapActivity).getCurrentSendPoi());
                            } else {
                                navMainView.showAppBackNavCommandFailToast(NavHolder.getInstance(mapActivity).getCurrentSendPoi());
                            }
                        }
                    }
                });
    }

    public void saveHistoryToSql(String requestId, PoiItemInfo poiItemInfo, String status, boolean isSave) {
        PoiHistoryInfo historyInfo = new PoiHistoryInfo();
        historyInfo.setPoiItemInfo(poiItemInfo);
        if (isSave) {
            historyInfo.setStatus("inProgress");
        } else {
            historyInfo.setStatus(status);
        }
        TBTHistoryImpl impl = new TBTHistoryImpl(mapActivity);
        impl.saveOrUpdateModelDestinationHistory(requestId, historyInfo, isSave);
    }

    /**
     * @param
     * @return void
     * @Title: saveSearchHistory
     * @Description: 保存到历史记录中
     */
    public void saveSearchHistory(PoiItemInfo poiItemInfo) {
        SearchHistoryImpl impl = new SearchHistoryImpl(mapActivity);
        impl.saveSearchHistory(poiItemInfo);
        RxBus.getDefault().post(RxConstants.ALL_PAGE_REFRESH, RxConstants.NAV_SAVE_POI);

    }

    public void deleteFav(PoiItemInfo poiItemInfo, int position) {
        if (navMainView != null) {
            navMainView.showDeleteDialog(poiItemInfo, position);
        }
    }

    public void deleteFavoriteDestination(final PoiItemInfo deletePoiItemInfo, final int position) {
        navService.doDeleteFavoriteDestination(deletePoiItemInfo)
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        if (navMainView != null) {
                            searchFavLists.remove(position);
                            navMainView.showSearchFav(searchFavLists);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        if (navMainView != null) {
                            navMainView.onResponseError((OnStarException) throwable);
                        }
                    }
                });
    }

    private List<FavoriteEntity> addCurrentLocationsToDestinationList(List<FavoriteEntity> favoriteEntities) {
        if (favoriteEntities == null) {
            favoriteEntities = new ArrayList<FavoriteEntity>();
        }
        Coordinate gpslt = new Coordinate();
        gpslt.setLatitude(-1);
        gpslt.setLongitude(-1);
        FavoriteEntity myLocation = new FavoriteEntity();
        myLocation.setPoiName(res.getString(R.string.poi_route_poi_str));
        myLocation.setFavoriteDestinationID(-1);
        myLocation.setPoiAddress("");
        myLocation.setPoiCoordinate(gpslt);
        favoriteEntities.add(0, myLocation);

        FavoriteEntity vehicleLocation = new FavoriteEntity();
        vehicleLocation.setPoiName(res.getString(R.string.poi_route_vehicle_str));
        vehicleLocation.setFavoriteDestinationID(-2);
        vehicleLocation.setPoiAddress("");
        Coordinate gpslv = new Coordinate();
        gpslv.setLatitude(-1);
        gpslv.setLongitude(-1);
        vehicleLocation.setPoiCoordinate(gpslv);
        favoriteEntities.add(1, vehicleLocation);
        return favoriteEntities;
    }

    public void showHomeCompPoi(String text, MapChoosePoiType mapChoosePoiType) {
        if (!BusinessUtil.checkDriverOrProxyAndShowDialog(mapActivity)) {
            return;
        }
        if (CommonUtil.isNull(text)) {
            NavSetAddressFragment comp = NavSetAddressFragment.newInstance(mapChoosePoiType);
            NavChoosePointInMapFragment compMap = NavChoosePointInMapFragment.newInstance(mapChoosePoiType);
            mapActivity.addFragment(fragmentManager, compMap, true);
            mapActivity.addFragment(fragmentManager, comp, true);
            mapActivity.showFragment(fragmentManager, NavSetAddressFragment.class, NavMainFragment.class);
        } else {
            String city = "";
            PoiItemInfo poiItemInfo = null;
            if (mapChoosePoiType == MapChoosePoiType.COMPANY) {
                poiItemInfo = mapActivity.getNavDataHolder().getMapCompChoosePoi();
                city = poiItemInfo.getCityName();
                if (DeviceUtil.getLanguage().equalsIgnoreCase("en")) {
                    LoadCityList cityList = new LoadCityList(mapActivity);
                    city = cityList.findByZhCity(city);
                }
                poiItemInfo.setCityName(city);
            } else if (mapChoosePoiType == MapChoosePoiType.HOME) {
                poiItemInfo = mapActivity.getNavDataHolder().getMapHomeChoosePoi();
                city = poiItemInfo.getCityName();
                if (DeviceUtil.getLanguage().equalsIgnoreCase("en")) {
                    LoadCityList cityList = new LoadCityList(mapActivity);
                    city = cityList.findByZhCity(city);
                }
                poiItemInfo.setCityName(city);
            }
            if (poiItemInfo != null) {
                mapActivity.showPoiToMap(poiItemInfo, LocationType.POI);
            }
        }
    }

    /**
     * @param
     * @return void
     * @Title: initUserAddressInfo
     * @Description: 初始化用户的家和公司的地址信息
     */
    public void initUserAddressInfo() {
        PoiItemInfo gohomePoiItemInfo;
        String home = "";
        String company = "";
        userAddressInfoList = mUserAddressInfoImpl.getAll();
        if (!CommonUtil.isNull(userAddressInfoList) && userAddressInfoList.size() > 0) {
            int listSize = userAddressInfoList.size();
            for (int i = 0; i < listSize; i++) {
                String customCatetory = userAddressInfoList.get(i).getCustomerCatetory();
                String userId = userAddressInfoList.get(i).getUserId();
                if (ApplicationUtil.getInstance().getIdpID().equals(userId)) {
                    if ("1".equals(customCatetory)) {// 家
                        gohomePoiItemInfo = getGoHomeOrCompanyPoiInfo(userAddressInfoList.get(i));
                        if (gohomePoiItemInfo != null) {
                            home = gohomePoiItemInfo.getTitle();
                            /**
                             * 缓存数据库家和公司的信息
                             */
                            mapActivity.getNavDataHolder().setMapHomeChoosePoi(gohomePoiItemInfo);
                        }
                    } else if ("2".equals(customCatetory)) {// 公司
                        gohomePoiItemInfo = getGoHomeOrCompanyPoiInfo(userAddressInfoList.get(i));
                        if (gohomePoiItemInfo != null) {
                            company = gohomePoiItemInfo.getTitle();
                            mapActivity.getNavDataHolder().setMapCompChoosePoi(gohomePoiItemInfo);
                        }
                    }
                }
            }
            if (navMainView != null) {
                navMainView.showHomeCompText(home, company);
            }
        }
    }


    public PoiItemInfo getGoHomeOrCompanyPoiInfo(UserAddressEntity userAddressEntity) {
        PoiItemInfo poiItemInfo = new PoiItemInfo();
        poiItemInfo.setTitle(userAddressEntity.getTitle());
        poiItemInfo.setAddress(userAddressEntity.getSnippet());
        poiItemInfo.setLatitude(userAddressEntity.getLatitude());
        poiItemInfo.setLongitude(userAddressEntity.getLongitude());
        poiItemInfo.setCityName(userAddressEntity.getPoiCityCode());
        poiItemInfo.setTelphone(userAddressEntity.getPoiPhoneNumber());
        return poiItemInfo;
    }

    @Override
    public void finish() {
        super.finish();
        mapHandler.removeOnMapSearchCallBack();
//        if (navMainPageSubscription != null && navMainPageSubscription.isUnsubscribed()) {
//            navMainPageSubscription.unsubscribe();
//            navMainPageSubscription = null;
//        }
    }
}
